package com.fkcai.hansoul.common.util;

import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

/**
 * 文件操作工具类
 */
public class FileUtil {
	// 允许的图片类型
	private static final Set<String> ALLOWED_IMAGE_TYPES = Set.of(
			"image/jpg", "image/jpeg", "image/png", "image/gif", "image/bmp", "image/webp"
	);
	
	// 允许的视频类型
	private static final Set<String> ALLOWED_VIDEO_TYPES = Set.of(
			"video/mp4", "video/avi", "video/mov", "video/mkv", "video/flv", "video/webm"
	);
	
	/**
	 * 从类路径加载文件为字节数组
	 *
	 * @param path 文件路径
	 * @return 文件内容字节数组
	 * @throws IOException 文件不存在或读取失败时抛出
	 */
	public static byte[] loadResourceAsBytes (String path) throws IOException {
		try (InputStream is = new ClassPathResource(path).getInputStream()) {
			if (is == null) {
				throw new IOException("文件不存在: " + path);
			}
			
			return is.readAllBytes();
		}
	}
	
	
	/**
	 * 验证文件类型是否合法
	 *
	 * @param file     文件
	 * @param fileType 文件类型
	 * @return 验证结果
	 */
	public static boolean validateFileType (MultipartFile file, String fileType) {
		String contentType = file.getContentType();
		if (contentType == null) return false;
		
		if ("image".equalsIgnoreCase(fileType)) {
			return ALLOWED_IMAGE_TYPES.contains(contentType);
		} else if ("video".equalsIgnoreCase(fileType)) {
			return ALLOWED_VIDEO_TYPES.contains(contentType);
		}
		
		return false;
	}
	
	
	/**
	 * 获取文件扩展名
	 *
	 * @param fileName 文件名
	 * @return 文件扩展名
	 */
	public static String getFileExtension (String fileName) {
		int lastIndexOfDot = fileName.lastIndexOf(".");
		
		if (lastIndexOfDot == -1) {
			return "";
		}
		
		return fileName.substring(lastIndexOfDot + 1);
	}
}
